﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Controls;
using Charts;
using System.Runtime.Serialization.Json;

namespace PhoneApp1
{

    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        List<Party> parties = new List<Party>();
        Grid twitGrid = new Grid();
        List<String> twitters;
        int callbackcount = 0;
        public static bool done;
        public MainPage()
        {
            InitializeComponent();
            twitGrid.Children.Add(new Pivot() { Title = "Twitter" });
            twitters = new List<string> {"pasok", "neademokratia", "syriza_gr", "laos_hellas", "dimokr_aristera", "dimsim_gr", "ecogreens", "greekliberals"};
            foreach (var twitter in twitters)
            {
                var request = (HttpWebRequest)WebRequest.CreateHttp("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&screen_name=" + twitter + "&count=20");
                request.BeginGetResponse(Callback, new object[]{request, twitter});
            }
            UpdateBoxes();
        }

        private void AddParty(TextBox name,TextBox percent)
        {
            try
            {
                parties.Add(new Party(name.Text, (int)(100 * Convert.ToDouble(percent.Text))));
            }
            catch (FormatException)
            {
                parties.Add(new Party(name.Text, 0));
            }
        }
        public void SetParties()
        {
            parties = new List<Party>();
            AddParty(Name1, Percent1);
            AddParty(Name2, Percent2);
            AddParty(Name3, Percent3);
            AddParty(Name4, Percent4);
            AddParty(Name5, Percent5);
            AddParty(Name6, Percent6);
            AddParty(Name7, Percent7);
            AddParty(Name8, Percent8);
            if (p9.Visibility == Visibility.Visible)
            {
                AddParty(Name9, Percent9);
            }
            if (p10.Visibility == Visibility.Visible)
            {
                AddParty(Name10, Percent10);
            }
        }
        public void PrintParties()
        {
            Seats1.Text = "" + parties[0].seats;
            Seats2.Text = "" + parties[1].seats;
            Seats3.Text = "" + parties[2].seats;
            Seats4.Text = "" + parties[3].seats;
            Seats5.Text = "" + parties[4].seats;
            Seats6.Text = "" + parties[5].seats;
            Seats7.Text = "" + parties[6].seats;
            Seats8.Text = "" + parties[7].seats;
            try
            {
                Seats9.Text = "" + parties[8].seats;
                Seats10.Text = "" + parties[9].seats;
            }
            catch (ArgumentOutOfRangeException) { }
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (p9.Visibility == Visibility.Collapsed)
            {
                p9.Visibility = Visibility.Visible;
            }
            else
            {
                p10.Visibility = Visibility.Visible;
                button1.Visibility = Visibility.Collapsed;
            }
        }
        private void AddSegment(PieChart pie, double percent, Color colour)
        {
            PieSegment segment = new PieSegment();
            segment.Percentage = percent;
            segment.Foreground = new SolidColorBrush(colour);
            pie.Segments.Add(segment);
        }
        private void UpdateBoxes()
        {
            
            SetParties();
            
            int max = 0;
            int count = 0;
            int seatcount = 0;
            int remaindercount = 0;
            foreach (Party item in parties)
            {
                item.remainder = 0;
                item.seats = -1;
                if (item.percent < 300)
                {
                    item.seats = 0;
                }
                else
                {
                    count += item.percent;
                    if (item.percent > max)
                    {
                        max = item.percent;
                    }
                }
            }

            foreach (Party item in parties)
            {
                if (item.seats != 0)
                {
                    item.seats = (item.percent * 260) / count;
                    item.remainder = item.percent - (item.seats * count) / 260;
                    if (item.percent == max)
                    {
                        item.seats += 40;
                    }
                    seatcount += item.seats;
                    remaindercount += item.remainder;
                }
            }

            while (seatcount < 300)
            {
                max = 0;
                foreach (Party item in parties)
                {
                    if (item.remainder > max)
                    {
                        max = item.remainder;
                    }
                }
                foreach (Party item in parties)
                {
                    if (item.remainder == max)
                    {
                        item.remainder -= count / 260;
                        remaindercount -= count / 260;
                        item.seats++;
                        seatcount++;
                    }
                }
            }
            double other = 0;
            foreach (Party party in parties)
            {
                other += party.percent;
            }
            other = 100 - other/100;
            if (other >= 0)
            {
                basicPie.Segments.Clear();
                parlPie.Segments.Clear();
                foreach (Party party in parties)
                {
                    AddSegment(basicPie, party.percent/100, party.colour);
                    AddSegment(parlPie, party.seats/3, party.colour);
                }

                AddSegment(basicPie, other, Colors.DarkGray); //other
            }
            PrintParties();
        }
        private void Name1_GotFocus(object sender, RoutedEventArgs e)
        {
            ((TextBox)sender).Foreground = new SolidColorBrush(Colors.Black);
            UpdateBoxes();
        }

        private void Name1_LostFocus(object sender, RoutedEventArgs e)
        {
            ((TextBox)sender).Foreground = (SolidColorBrush)Resources["PhoneForegroundBrush"];
        }

        private void Callback(IAsyncResult result)
        {
            try
            {
                var request = ((HttpWebRequest)(((object[])result.AsyncState)[0]));
                var response = request.EndGetResponse(result);
                var stream = response.GetResponseStream();
                var serializer = new DataContractJsonSerializer(typeof(List<RootObject>));
                var json = serializer.ReadObject(stream);
                var twits = (List<RootObject>)json;
                Dispatcher.BeginInvoke(() =>
                {
                    var viewer = new ScrollViewer();
                    var panel = new StackPanel();
                    viewer.Content = panel;
                    var item = new PivotItem() { Header = (string)((object[])result.AsyncState)[1], Content = viewer };
                    ((Pivot)(twitGrid).Children[0]).Items.Add(item);
                    foreach (var twit in twits)
                    {
                        panel.Children.Add(new TextBlock() {TextWrapping = TextWrapping.Wrap, Text = twit.text, FontSize = 26, Margin = new Thickness() { Top = 35 } });
                    }
                });
                callbackcount++;
                if (callbackcount == twitters.Count)
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        Twitter.grid = twitGrid;
                        wait.Visibility = System.Windows.Visibility.Collapsed;
                        done = true;
                    });
                }
            }
            catch (WebException) { callbackcount++; }
            catch (ArgumentNullException) { callbackcount++; }
        }

       private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (done && ((Panorama)sender).SelectedIndex == 2)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri("/Twitter.xaml", UriKind.Relative));
                });
            }
        }
    }
    public class Party
    {
        public string name;
        public int percent;
        public int seats = -1;
        public int remainder;
        public Color colour;
        public Party(string name, int percent)
        {
            this.name = name;
            this.percent = percent;
            colour = GetColour(name);

        }
        public static Color GetColour(string name)
        {
            switch(name)
            {
                case "ΠΑΣΟΚ":
                    return Colors.Green;
                case "ΝΔ":
                    return Colors.Cyan;
                case "KKE":
                    return Colors.Red;
                case "ΣΥΡΙΖΑ":
                    return Colors.Orange;
                case "ΛΑΟΣ":
                    return Colors.Blue;
                case "ΔΑ":
                    return Colors.Magenta;
                case "ΔΣ":
                    return Colors.Purple;
                case "Πρασ.":
                    return Colors.Green;
            }
            return Colors.DarkGray;
        }
    }
}














